<!-- 加班列表 -->
<template>
  <ContainerLayout class="overitem-list">
    <div class="form-container">
      <el-form ref="formRef" :inline="true" :model="queryForm" class="query-form" label-width="40px">
        <el-form-item label="用户" v-if="false">
          <el-input v-model="queryForm.user" clearable placeholder="请输入" style="width: 100px" />
        </el-form-item>
        <el-form-item label="部门" v-if="false">
          <el-cascader :options="deptList" :props="deptProps" style="width: 290px" v-model="queryForm.deptIds" collapse-tags clearable />
        </el-form-item>
        <el-form-item label="项目">
          <el-select v-model="queryForm.projectId" placeholder="请选择项目" clearable style="width: 160px">
            <el-option v-for="item in projectList" :key="item.code" :label="`${item.code}-${item.cname}`" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryForm.overtimeStatus" placeholder="请选择状态" clearable style="width: 130px">
            <el-option v-for="item in overtimeStatusOptions" :key="item.value" :label="`${item.label}`" :value="item.value" />
          </el-select>
        </el-form-item>
        <TimeSlotDatePicker label="时段" v-model="queryForm.date" />
        <el-form-item>
          <el-button type="primary" @click="handleClickBtnSubmit" :icon="Search">查询</el-button>
          <el-button @click="handleClickBtnReset" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="button-toolbar">
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button plain size="small" type="success" @click="handleClickBtnUpdateOvertimeStatus(overtimeStatusEnum.部门领导通过)" :icon="Select">批量通过</el-button>
          <el-button plain size="small" type="danger" @click="handleClickBtnUpdateOvertimeStatus(overtimeStatusEnum.已驳回)" :icon="CloseBold">批量不通过</el-button>
          <el-button plain size="small" type="primary" :icon="Download" v-if="false">导出</el-button>
        </el-col>
      </el-row>
    </div>
    <div class="table-container">
      <div class="table-wrap" ref="tableWrap">
        <el-table :data="tableData" @selection-change="handleSelectionChange" scrollbar-always-on style="width: 100%" border :height="tableHeight" header-cell-class-name="table-header-row" empty-text="没有数据">
          <el-table-column type="selection" :selectable="selectable" width="55" fixed />
          <el-table-column prop="deptName" label="部门" width="120" fixed />
          <el-table-column prop="userNick" label="姓名" width="150" fixed />
          <el-table-column label="项目" show-overflow-tooltip width="250">
            <template #default="scope">
              {{ getProjectName(scope.row.projectId) }}
            </template>
          </el-table-column>

          <el-table-column label="时段">
            <el-table-column label="开始时间" prop="startTime" width="200" />
            <el-table-column label="结束时间" prop="endTime" width="200" />
          </el-table-column>
          <el-table-column prop="durationTime" label="时长" width="150">
            <template #default="scope">
              <el-text>
                <el-icon>
                  <Clock />
                </el-icon>
                {{ scope.row.durationTime }}
              </el-text>
            </template>
          </el-table-column>

          <el-table-column label="状态" width="150">
            <template #default="scope">
              <el-tag :type="overtimeStatus[scope.row.overtimeStatus][1]"> {{ overtimeStatus[scope.row.overtimeStatus][0] }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="remark" label="工作内容" width="350">
            <template #default="scope">
              <div class="remark-content">
                {{ scope.row.remark }}
              </div>
            </template>
          </el-table-column>
          <el-table-column />
          <el-table-column label="审批" width="150" fixed="right">
            <template #default="scope">
              <el-button v-if="false" link type="danger" size="small" :icon="Delete">删除</el-button>
              <el-button link type="success" @click="handleClickBtnUpdateOvertimeStatus(overtimeStatusEnum.部门领导通过, scope.row)" size="small" :icon="Select">通过</el-button>
              <el-button link type="warning" @click="handleClickBtnUpdateOvertimeStatus(overtimeStatusEnum.已驳回, scope.row)" size="small" :icon="CloseBold">已驳回</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </ContainerLayout>
</template>
<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import ContainerLayout from '../layout/ContainerLayout.vue'
import * as utils from '../utils'
import http from '../http'
import { useDeptStore, useProjectssStore, useUsersStore } from '../stores'
import { Refresh, Search, Clock, Download, Select, CloseBold, Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { overtimeStatusEnum, overtimeStatus } from '../definitions/status'
import TimeSlotDatePicker from '../layout/FormTableLayout/TimeSlotDatePicker.vue'

const deptList = ref(useDeptStore().getAllState())
const deptProps = ref({ multiple: true, label: 'deptName', value: 'deptId' })
const tableData = ref<any[]>([])
const tableColumnDate = ref<any[]>([])
const tableWrap = ref<HTMLElement | null>(null)
const tableHeight = ref(500)
const multipleSelection = ref<any[]>([])
const selectable = (row: any) => row.status !== 1

const projectList = ref<Array<{ id: number; code: string; cname: string }>>(useProjectssStore().getAllState() as any)
const queryForm = reactive({
  user: '',
  projectId: null,
  date: [] as Date[],
  deptIds: [] as any[] | number[],
  overtimeStatus: null,
})

const overtimeStatusOptions = ref<any[]>([])
Object.keys(overtimeStatusEnum).map((value: any) => {
  const label = overtimeStatusEnum[value]
  if (typeof label === 'string' && value !== '3') {
    overtimeStatusOptions.value.push({
      label,
      value,
    })
  }
})
/**
 * 获取考勤分类列表
 *
 * @returns {Promise<void>}
 */
const getClockinCategoryList = async () => {
  const [start, end] = queryForm.date
  // 设置 table 列
  tableColumnDate.value = utils.generateDates(start, end)

  const params = {
    pageSize: 99999,
    // startClockinDate: utils.formatDate(start, 'yyyy-MM-dd'),
    // endClockinDate: utils.formatDate(end, 'yyyy-MM-dd'),
    userName: useUsersStore().user.username,
  }
  if (queryForm.overtimeStatus) {
    Object.assign(params, { overtimeStatus: queryForm.overtimeStatus })
  }
  if (queryForm.projectId) {
    Object.assign(params, { projectId: queryForm.projectId })
  }
  if (queryForm.user !== '') {
    Object.assign(params, { userName: queryForm.user })
  }

  const { rows } = await http({
    method: 'GET',
    path: '/dev-api/oa/overtime/list',
    params,
  })
  tableData.value = rows
  nextTick(() => {
    const tableWrapElement = tableWrap.value
    if (tableWrapElement) {
      // 设置表格高度
      tableHeight.value = tableWrapElement.offsetHeight
    }
  })
}
/**
 * 重置表单
 *
 * 重置查询表单的所有字段到初始状态，包括用户、项目ID、日期范围、部门ID数组和时间日志类别
 */
const resetForm = () => {
  tableData.value = []
  const [start, end] = utils.getDateRangeByDate(utils.shortcutsType.本月) as Date[]
  queryForm.user = ''
  queryForm.projectId = null
  queryForm.date = [start, end]
  queryForm.deptIds = [] as string[] | number[]
  queryForm.overtimeStatus = null
  handleClickBtnSubmit()
}
/**
 * 处理点击提交按钮的事件
 *
 * 异步调用获取打卡分类列表的函数
 */
const handleClickBtnSubmit = async () => {
  await getClockinCategoryList()
}

/**
 * 处理点击重置按钮的事件
 *
 * 调用 resetForm 函数重置表单
 */
const handleClickBtnReset = async () => {
  await resetForm()
}

const getProjectName = (id: any) => {
  const item = projectList.value.find((item) => item.id == id)
  return item?.cname || ''
}

const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}

const handleClickBtnUpdateOvertimeStatus = async (status: number, row: any | null = null) => {
  let ids: any[] = []
  if (!row) {
    if (multipleSelection.value.length === 0) return ElMessage.warning('请选择要操作的记录')
    ids = multipleSelection.value.map((obj) => obj.id)
  } else {
    ids = [row.id]
  }

  const { code } = await http({
    method: 'PUT',
    path: '/dev-api/oa/overtime/approved',
    params: {
      ids,
      overtimeStatus: status,
      updateBy: useUsersStore().user.username,
    },
  })
  if (code == 200) {
    ElMessage.success('操作成功')
    await handleClickBtnSubmit()
  }
}

onMounted(async () => {
  await handleClickBtnReset()
  await handleClickBtnSubmit()
})
</script>
<style lang="scss" scoped>
.overitem-list {
  display: flex;
  flex-direction: column;
  .form-container {
    display: flex;
    justify-content: flex-start;
  }
  .table-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    .table-wrap {
      flex: 1;
    }
  }
  .button-toolbar {
    margin-bottom: 18px;
  }
  .table-header-cell {
    writing-mode: vertical-lr;
  }
  .remark-content {
    width: 100%;
    height: 100%;
    white-space: pre-line;
  }
}
</style>
